﻿using System;
using System.Runtime.InteropServices;

namespace vis_client
{
	public delegate void MethodInvoker();

	public class SimData
	{
		protected static SimData _Instance = null;

		//protected byte[] _Frame = null;
		protected IntPtr _Frame;
		protected int _FrameWidth = 0;
		protected int _FrameHeight = 0;

		protected SimData()
		{
		}

		protected SimData(int frameWidth, int frameHeight)
		{
			_FrameWidth = frameWidth;
			_FrameHeight = frameHeight;
			_Frame = Marshal.AllocHGlobal(_FrameWidth * _FrameHeight * 4);
			//_Frame = new byte[_FrameWidth * _FrameHeight * 4];
		}

		~SimData()
		{
			Marshal.FreeHGlobal(_Frame);
		}

		public IntPtr Frame
		{
			get { return _Frame; }
		}

		public int FrameWidth
		{
			get { return _FrameWidth; }
		}

		public int FrameHeight
		{
			get { return _FrameHeight; }
		}

		public static SimData GetCurData() { return _Instance; }

		public static void UpdateFrame(byte[] data, int width, int height)
		{
			if (data != null && width > 0 && height > 0)
			{
				if (_Instance == null)
					_Instance = new SimData(width, height);
				else if (_Instance.FrameWidth != width || _Instance.FrameHeight != height)
					_Instance = new SimData(width, height);

				Marshal.Copy(data, 0, _Instance._Frame, width * height * 4);
				//Array.Copy(data, _Instance._Frame, width * height * 4);
			}
		}

		public static event MethodInvoker FrameSizeChanged;

		protected static void OnFrameSizeChanged()
		{
			if (SimData.FrameSizeChanged != null)
				SimData.FrameSizeChanged();
		}
	}
}
